/**   
* @Title: CollectBillController.java 
* @Package cn.kxm.controller 
* @Description: TODO(用一句话描述该文件做什么) 
* @author 初雨泽
* @date 2018年10月16日 下午3:03:20   
*/
package cn.kxm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import cn.kxm.pojo.OutstorageBill;
import cn.kxm.pojo.CollectBill;
import cn.kxm.pojo.CollectBillDetail;
import cn.kxm.service.OutstorageBillService2;
import cn.kxm.service.CollectBillDetailService;
import cn.kxm.service.CollectBillService;
import cn.kxm.util.ExcelUtil;
import cn.kxm.util.MakeNewCode;
import cn.kxm.util.WorderToNewWordUtils;

/** 
* @ClassName: CollectBillController 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author 初雨泽
* @date 2018年10月16日 下午3:03:20 loadInstroageListByCollectBill
*  
*/
@Controller
@RequestMapping("collectBillController")
@SessionAttributes(value= {"collectCode","collectBill"})
public class CollectBillController {
	@Autowired
	private CollectBillService collectBillService;

	@Autowired
	private CollectBillDetailService collectBillDetailService;

	@Autowired
	private OutstorageBillService2 outstorageBillService;

	@Autowired
	private MakeNewCode makeNewCode;

	/** 
	 * @Title: reLoadDatagird 
	 * @Description: 显示collectbill数据表
	 * @param page
	 * @param rows
	 * @param findcode
	 * @param findstartDate
	 * @param findendDate
	 * @param findsupplierName
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("reLoadDatagird")
	@ResponseBody
	public Object reLoadDatagird(Integer page,Integer rows,
			@RequestParam(required=false) String findcode,
			@RequestParam(required=false) String findstartDate,
			@RequestParam(required=false) String findendDate,
			@RequestParam(required=false) String findsupplierName) {
		System.out.println("reLoadData");
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", collectBillService.searchCollectBill(page, rows, findcode, findstartDate, findendDate, findsupplierName));
		map.put("total", collectBillService.countSearchCollectBill(findcode, findstartDate, findendDate, findsupplierName));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: beforeAddCollectBill 
	 * @Description: 添加表单前的处理订单号方法
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("beforeAddCollectBill")
	@ResponseBody
	public Object beforeAddCollectBill() {
		System.out.println("beforeAddCollectBill");
		Map<String,Object> map=new HashMap<String, Object>();
		String code=makeNewCode.getRandomCodeByPrefix("SK");
		map.put("code", code);
		System.out.println(code);
		return JSON.toJSON(map);
	}


	/** 
	 * @Title: findCompanyCollectBill 
	 * @Description: 装载供应商数据表格
	 * @param page
	 * @param rows
	 * @param name
	 * @param code
	 * @param type
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("companyCollectBill")
	@ResponseBody
	public Object findCompanyCollectBill(Integer page,Integer rows,
			@RequestParam(value="name",required=false) String name,
			@RequestParam(value="code",required=false) String code,
			@RequestParam(value="type",required=false) Integer type) {
		System.out.println("name:"+name+"   code:"+code+"  type:"+type);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", collectBillService.searchCompany(code, name, type, page, rows));
		map.put("total", collectBillService.countSearchCompany(code, name, type));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: findCollectBillDetail 
	 * @Description: 查询collectbill并查询collectbilldetail,通过detail查询入库单,并放入session
	 * @param collectCode
	 * @param model
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("findCollectBill")
	@ResponseBody
	public String findCollectBillDetail(@RequestParam("collectCode") String collectCode,Model model) {
		System.out.println("findCollectBill");
		model.addAttribute("collectBill", collectBillService.findCollectBill(collectCode));
		model.addAttribute("collectCode", collectCode);
		return "success";
	}

	/** 
	 * @Title: loadCollectBillDetail 
	 * @Description: 装载collectbill详情表单数据
	 * @param collectbill
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadCollectBill")
	@ResponseBody
	public Object loadCollectBillDetail(@ModelAttribute("collectBill") CollectBill collectbill,ModelMap model) {
		Map<String,Object> map=new HashMap<String, Object>();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(collectbill.getCollectDate());
		map.put("code", collectbill.getCode());
		map.put("collectDate", dateString);
		map.put("customName", collectbill.getCustomName());
		map.put("type", collectbill.getCollectType());
		map.put("collectTotalMoney", collectbill.getCollectTotalMoney());
		map.put("memo", collectbill.getMemo());
		model.remove("collectBill");
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: loadDetailInFirstPage 
	 * @Description: 在首页加载collectbilldetail
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadDetailInFirstPage")
	@ResponseBody
	public Object loadDetailInFirstPage(@RequestParam("code") String code) {
		List<CollectBillDetail> list=collectBillDetailService.findCollectBillDetail(code);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", list);
		return JSON.toJSON(map);
	}

	/** 
	 * @Title: loadOutstorageListByCollectBill 
	 * @Description: 加载collectbill中的入库单
	 * @param list
	 * @param model
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadOutstorageListByCollectBill")
	@ResponseBody
	public Object loadOutstorageListByCollectBill(@ModelAttribute("collectCode") String collectCode,
			Integer page,Integer rows) {
		System.out.println("loadOutstorageListByCollectBill");
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", collectBillDetailService.findCollectBillDetail(collectCode));
		/*map.put("total",outstorageBillService.countOutstorageBillByCollectBillCode(collectCode));*/
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: revokeCollectBill 
	 * @Description: 撤销审核状态
	 * @param code
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("revokeCollectBill")
	@ResponseBody
	public Object revokeCollectBill(@RequestParam("code") String code) {
		collectBillService.updateCollectBillType(code, 1);

		//
		List<CollectBillDetail> list=collectBillDetailService.findCollectBillDetail(code);
		List<OutstorageBill> outstorageBillList=new ArrayList<OutstorageBill>();
		for (CollectBillDetail a:list) {
			System.out.println("a.getBillCode:"+a.getBillCode());
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				outstorageBillList.add(outstorageBillService.findCollectBillDetail(billCode));
			}
			/*collectBillDetailService.deleteRealMoneyByCollectBillDetail(a.getId());*/
		}
		/*for(OutstorageBill a:outstorageBillList) {
			if(a!=null) {
				outstorageBillService.updateOutstorageBillType(a.getCode(), 1);
			}
		}*/
		System.out.println("successRevoke");
		String result="success";
		return result;
	}

	/** 
	 * @Title: loadUnselectedOutstorageBill 
	 * @Description: 加载未被选择的入库单供collectbill选择
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadUnselectedOutstorageBill")
	@ResponseBody
	public Object loadUnselectedOutstorageBill(Integer page,Integer rows,
			@RequestParam(required=false) String findcode,
			@RequestParam(required=false) String findstartDate,
			@RequestParam(required=false) String findendDate,
			@RequestParam(required=false) String findsupplierName,
			@RequestParam(required=false) String collectCode) {
		System.out.println("loadUnselectedOutstorageBill");
		System.out.println("findsupplierName:"+findsupplierName);
		System.out.println("page:"+page);
		System.out.println("rows:"+rows);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", outstorageBillService.findUnselectedOutstorageBill(page, rows, findcode, findstartDate, findendDate, findsupplierName,collectCode));
		map.put("total", outstorageBillService.countUnselectedOutstorageBill(findcode, findstartDate, findendDate, findsupplierName,collectCode));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: saveCollectBillDetailToDataBase 
	 * @Description: 保存collectbill和collectbill 的入库单outstoragebill
	 * @param data
	 * @param collectCode
	 * @param collectData
	 * @param collectType
	 * @param memo
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("saveCollectBillDetailToDataBase")
	@ResponseBody
	public String saveCollectBillDetailToDataBase(@RequestParam("saveRows") String data,
			@RequestParam("collectCode") String collectCode,
			@RequestParam("collectData") String collectData,
			@RequestParam("collectType") String collectType,
			@RequestParam("memo") String memo,
			@RequestParam("collectTotalMoney") String collectTotalMoney) {
		System.out.println("saveCollectBillDetailToDataBase");
		System.out.println("collectTotal:"+collectTotalMoney);
		//处理outstoragebill部分
		List<CollectBillDetail> list=(List<CollectBillDetail>) JSONArray.parseArray(data, CollectBillDetail.class);
		/*List<CollectBillDetail> list_detail=new ArrayList<CollectBillDetail>();
		for(int i=0;i<list.size();i++) {
			CollectBillDetail p=new CollectBillDetail();
			p.setBillCode(list.get(i).getCode());
			p.setMemo(list.get(i).getMemo());
			p.setCollectCode(collectCode);
			p.setCollectMoney(list.get(i).getMoney());
			p.setRealMoney(0.00);
			list_detail.add(p);
		}*/
		collectBillDetailService.deleteDetailListByCollectBill(collectCode);
		collectBillDetailService.addDetailListByCollectBill(list,collectCode);
		//处理表单部分
		System.out.println("collectType"+collectType);
		Integer collectType_i=Integer.parseInt(collectType);
		Float collectTotalMoney_f=Float.parseFloat(collectTotalMoney);
		collectBillService.updateCollectBill(collectData, collectType_i, memo, collectCode, collectTotalMoney_f);
		return "success";
	}

	/** 
	 * @Title: collectCurrentCollectBill 
	 * @Description: 未支付collectbill的审核方法
	 * @param code
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("collectCurrentCollectBill")
	@ResponseBody
	public String collectCurrentCollectBill(@RequestParam("code") String code) {
		System.out.println("collectCurrentCollectBill");
		collectBillService.updateCollectBillType(code, 2);
		List<CollectBillDetail> list=collectBillDetailService.findCollectBillDetail(code);
		List<OutstorageBill> outstorageBillList=new ArrayList<OutstorageBill>();
		for (CollectBillDetail a:list) {
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				outstorageBillList.add(outstorageBillService.findCollectBillDetail(billCode));
			}
			/*collectBillDetailService.addRealMoneyByCollectBillDetail(a.getId());*/
		}
		/*for(OutstorageBill a:outstorageBillList) {
			if(a!=null) {
				outstorageBillService.updateOutstorageBillType(a.getCode(), 2);
			}
		}*/
		System.out.println("successCheck");
		String result="success";
		return result;
	}

	/** 
	 * @Title: realCollectCurrentBill 
	 * @Description: 支付方法
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("realCollectCurrentBill")
	@ResponseBody
	public String realCollectCurrentBill(@RequestParam("code") String code) {
		System.out.println("collectCurrentCollectBill");
		collectBillService.updateCollectBillType(code, 3);
		List<CollectBillDetail> list=collectBillDetailService.findCollectBillDetail(code);
		List<OutstorageBill> outstorageBillList=new ArrayList<OutstorageBill>();
		for (CollectBillDetail a:list) {
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				outstorageBillList.add(outstorageBillService.findCollectBillDetail(billCode));
			}
			collectBillDetailService.addRealMoneyByCollectBillDetail(a.getId());
		}
		for(OutstorageBill a:outstorageBillList) {
			if(a!=null) {
				outstorageBillService.updateOutstorageBillType(a.getCode(), 2);
				outstorageBillService.updateSellorderPayStatus(outstorageBillService.findOrderCodeFromOutstorDetail(a.getCode()),2);
			}
		}
		System.out.println("successCollect");
		String result="success";
		return result;
	}

	/** 
	 * @Title: revokeRealCollectCurrentBill 
	 * @Description: 撤销支付方法
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("revokeRealCollectCurrentBill")
	@ResponseBody
	public String revokeRealCollectCurrentBill(@RequestParam("code") String code) {
		collectBillService.updateCollectBillType(code, 2);

		//
		List<CollectBillDetail> list=collectBillDetailService.findCollectBillDetail(code);
		List<OutstorageBill> outstorageBillList=new ArrayList<OutstorageBill>();
		for (CollectBillDetail a:list) {
			System.out.println("a.getBillCode:"+a.getBillCode());
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				outstorageBillList.add(outstorageBillService.findCollectBillDetail(billCode));
			}
			collectBillDetailService.deleteRealMoneyByCollectBillDetail(a.getId());
		}
		for(OutstorageBill a:outstorageBillList) {
			if(a!=null) {
				outstorageBillService.updateOutstorageBillType(a.getCode(), 1);
				outstorageBillService.updateSellorderPayStatus(outstorageBillService.findOrderCodeFromOutstorDetail(a.getCode()),1);
			}
		}
		System.out.println("successRevoke");
		String result="success";
		return result;
	}

	/** 
	 * @Title: addCollectBill 
	 * @Description: 添加一个collectbill
	 * @param code
	 * @param collectDate
	 * @param customName
	 * @param collectType
	 * @param collectTotalMoney
	 * @param memo
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("addCollectBill")
	@ResponseBody
	public String addCollectBill(@RequestParam("code") String code,
			@RequestParam("collectDate") String collectDate,
			@RequestParam("customName") String customName,
			@RequestParam("collectType") String collectType,
			@RequestParam("collectTotalMoney") String collectTotalMoney,
			@RequestParam("memo") String memo) {
		System.out.println("addCollectBill");
		CollectBill newCollectBill=new CollectBill();
		newCollectBill.setCode(code);
		newCollectBill.setCustomName(customName);
		newCollectBill.setMemo(memo);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date=null;
		try {
			date=format.parse(collectDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		newCollectBill.setCollectDate(date);
		newCollectBill.setCollectTotalMoney(Double.parseDouble(collectTotalMoney));
		newCollectBill.setCollectType(Integer.parseInt(collectType));
		System.out.println("newCollectBill+++++"+newCollectBill);
		collectBillService.addCollectBill(newCollectBill);
		return "success";
	}

	/** 
	 * @Title: deleteCollectBill 
	 * @Description: 删除collectBill
	 * @param code
	 * @param collectStatus
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("deleteCollectBill")
	@ResponseBody
	public String deleteCollectBill(@RequestParam("collectCode") String code,
			@RequestParam("collectStatus") String collectStatus) {
		System.out.println("deleteCollectBill");
		Integer collectStatus_i=Integer.parseInt(collectStatus);
		if(collectStatus_i==1) {
			//未付款
			collectBillService.deleteCollectBillUnchecked(code);
		}else {
			//已付款
			collectBillService.deleteCollectBillChecked(code);
		}
		return "success";
	}

	/** 
	 * @Title: export 
	 * @Description: 生成excel文件
	 * @param request
	 * @param response
	 * @throws Exception  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	@RequestMapping("getExcel")
	public void export(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//获取数据
		List<CollectBill> list=collectBillService.findAllCollectBill();
		/*List<CollectBill> list=new ArrayList<CollectBill>();
		for(int i=0;i<2;i++) {
			CollectBill p=new CollectBill();
			p.setCode(String.valueOf(i));
			p.setCustomName("qwe");
			p.setMemo("123");
			p.setCollectDate(new Date());
			p.setCollectStatus(1);
			p.setCollectTotalMoney(2);
			p.setCollectType(2);
			list.add(p);
		}*/
		System.out.println(list);

		//excel标题
		String[] title= {"收款单号","收款日期","单位名称","收款金额","收款方式","收款状态","备注"};
		System.out.println(title);

		//excel文件名
		String fileName="采购收款管理"+new Date()+".xls";
		System.out.println(fileName);

		//sheet名
		String sheetName="采购收款管理";
		System.out.println(sheetName);

		//装载数据
		String[][] content=new String[list.size()][title.length];
		for(int i=0;i<list.size();i++) {
			CollectBill p=list.get(i);
			content[i][0]=p.getCode();
			content[i][1]=(p.getCollectDate()).toString();
			content[i][2]=p.getCustomName();
			content[i][3]=String.valueOf(p.getCollectTotalMoney());
			if(p.getCollectType()==1) {
				content[i][4]="现金";
			}else {
				content[i][4]="转账";
			}
			if(p.getCollectStatus()==1) {
				content[i][5]="未审核";
			}else if(p.getCollectStatus()==2){
				content[i][5]="已审核";
			}else if(p.getCollectStatus()==3){
				content[i][5]="已收款";
			}
		}
		System.out.println(String.valueOf(content));

		//创建HSSF
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
		System.out.println(wb);

		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/** 
	 * @Title: setResponseHeader 
	 * @Description: 发送响应流方法
	 * @param response
	 * @param fileName  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(),"ISO8859-1");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	/** 
	 * @Title: getWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param code
	 * @param request
	 * @param response  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	@RequestMapping("getWord")
	public void getWord(@RequestParam("code") String code,HttpServletRequest request,HttpServletResponse response) {
		System.out.println(code);

		// 获取应用的根路径
		String servletContextRealPath = request.getServletContext().getRealPath("");
		// 获取模板文件
		File templateFile = new File(servletContextRealPath + "/wordModel/collectBillWordModel.docx");
		FileInputStream in=null;
		try {
			in = new FileInputStream(templateFile);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		//生成word文件名
		String fileName="烟台凯旋科技有限公司采购收款单"+new Date()+".docx";

		//$替换对象
		CollectBill p=collectBillService.findCollectBill(code);
		Map<String,String> testMap=new HashMap<String, String>();
		testMap.put("code", p.getCode());
		testMap.put("customName", p.getCustomName());
		testMap.put("collectTotalMoney", Double.toString(p.getCollectTotalMoney()));
		testMap.put("collectDate", p.getCollectDate().toString());
		if(p.getCollectType()==1) {
			testMap.put("collectType", "现金");
		}else {
			testMap.put("collectType", "转账");
		}
		testMap.put("memo", p.getMemo());

		Double all=0.00;
		//需插入表格替换对象
		List<String[]> testList = new ArrayList<String[]>();
		List<CollectBillDetail> collectBillDetailList= collectBillDetailService.findCollectBillDetail(code);
		for(int i=0;i<collectBillDetailList.size();i++) {
			CollectBillDetail ins=collectBillDetailList.get(i);
			testList.add(new String[]{ins.getBillCode(),"应收账目","增加",String.valueOf(ins.getCollectMoney()),String.valueOf(ins.getRealMoney()),ins.getMemo()});
			all+=ins.getCollectMoney();
		}
		//写入合计金额
		testMap.put("all", String.valueOf(all));
		WorderToNewWordUtils util=new WorderToNewWordUtils();
		XWPFDocument doc= util.changWord(in, testMap, testList, 5);
		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			doc.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
